package com.xiaolei.fastnio.http.Adapter

import com.xiaolei.fastnio.http.Comm.RequestMethod
import com.xiaolei.fastnio.http.Route
import com.xiaolei.fastnio.http.onRoute
import com.xiaolei.fastnio.library.Factorys.IClientAdapterFactory
import com.xiaolei.fastnio.http.Ext.elseOr
import com.xiaolei.fastnio.http.Ext.ifTrue
import java.util.*
import java.util.concurrent.ConcurrentHashMap

/**
 * Http会话的工厂类
 */
class HttpClientAdapterFactory : IClientAdapterFactory<HttpClientAdapter>
{
    /**
     * 映射Uri和onRoute之间的缓存
     */
    private val routeMap = ConcurrentHashMap<String, LinkedList<Route>>()

    // 首页的Uri
    var indexUri = "/index.html"
        set(value)
        {
            field = value ifTrue { it.startsWith("/") } elseOr "/$value"
        }

    /**
     * 主要保存 UUID与客户端Adapter的关系
     */
    private val cache = ConcurrentHashMap<String, HttpClientAdapter>()

    /**
     * 注册uri和Route的关系
     */
    fun registerRoute(uri: String, vararg methods: RequestMethod, route: onRoute)
    {
        val realUri = uri ifTrue { it.startsWith("/") } elseOr "/$uri"
        if (realUri == "/")
        {
            indexUri = realUri
        }
        val routes = routeMap[realUri] ?: LinkedList()
        if (!routeMap.contains(route))
        {
            routeMap[realUri] = routes
        }
        for (method in methods)
        {
            routes.add(Route(method, onRoute = route))
        }
    }

    /**
     * 根据sessionId自动生成客户端的Adapter
     * 如果有，则是获取
     */
    override fun get(ssId: String): HttpClientAdapter
    {
        var adapter = cache[ssId]
        if (adapter == null)
        {
            adapter = HttpClientAdapter(routeMap, indexUri)
            cache[ssId] = adapter
        }
        return adapter
    }

    override fun has(ssId: String): Boolean
    {
        return cache.contains(ssId)
    }

    /**
     * 移除关系，大多数是因为客户端关闭了
     */
    override fun remove(ssId: String)
    {
        cache.remove(ssId)
    }
}